package com.hrbxlh.doccheck.controller;

import com.hrbxlh.doccheck.domain.SimilarFile;
import com.hrbxlh.doccheck.service.DocCheckService;
import com.hrbxlh.doccheck.vo.SimilarFileVO;
import com.hrbxlh.util.CascaderVO;
import com.hrbxlh.util.Result;
import com.hrbxlh.virtualization.exception.GlobalException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import static com.hrbxlh.doccheck.constant.DocCheckConstant.MAX_UPLOAD_SIZE;
import static com.hrbxlh.doccheck.constant.DocCheckConstant.MAX_UPLOAD_SIZE_MESSAGE;


/**
 * @author cheer
 */
@RestController
@RequestMapping("/doc-check")
public class DocCheckController {


    @Autowired
    private DocCheckService docCheckService;

    @PostMapping("/upload")
    @ResponseBody
        public Result uploadFile(MultipartFile file,@RequestParam String userId) throws Exception {
        if (file.getSize() > MAX_UPLOAD_SIZE) {
            throw new Exception("上传文件过大");
        }
        docCheckService.uploadFile(userId, file);
        return Result.success();
    }

    @GetMapping("/view")
    @ResponseBody
    public Result<List<CascaderVO>> viewFile(@RequestParam String  userId) {
        List<CascaderVO> fileTree = docCheckService.viewFile(userId);
        return Result.success(fileTree);
    }

    @GetMapping
    @ResponseBody
    public Result<List<SimilarFileVO>> queryFile(@RequestParam Double similarity,@RequestParam String userId) {
        List<SimilarFile> similarFiles = docCheckService.querySimilarFile(userId, similarity);

        List<SimilarFileVO> similarFileVOs = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(similarFiles)) {
            DecimalFormat df = new DecimalFormat("0.00%");
            for (SimilarFile similarFile : similarFiles) {
                SimilarFileVO similarFileVO = SimilarFileVO.builder()
                        .file(similarFile.getFile())
                        .comparedFile(similarFile.getComparedFile())
                        .similarity(df.format(similarFile.getSimilarityScore()))
                        .build();
                similarFileVOs.add(similarFileVO);
            }
        }

        return Result.success(similarFileVOs);
    }
}
